import DataServe from '@/api/search'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { Suggestion, Histories, SearchResults, Article } from '@/types/data'
import { AppDispatch } from '@/types/store'
import { setHistoryStorage, getHistoryStorage } from '@/utils/storage'

const searchSlice = createSlice({
  name: 'search',
  initialState: {
    suggestion: [] as Suggestion,
    histories: getHistoryStorage() as Histories,
    result: {
      results: [] as Array<Article>,
      total_count: 1
    }
  },
  reducers: {
    setSuggestion(state, action: PayloadAction<Suggestion>) {
      state.suggestion = action.payload
    },
    setHistories(state, action: PayloadAction<string>) {
      const { payload } = action
      const newHistories = state.histories.filter((item) => item !== payload)
      newHistories.unshift(payload)
      if (newHistories.length > 10) {
        newHistories.pop()
      }
      state.histories = newHistories
      setHistoryStorage(newHistories)
    },
    clearHistories(state) {
      state.histories = []
      setHistoryStorage([])
    },
    delHistory(state, action: PayloadAction<string>) {
      const { payload } = action
      const newHistories = state.histories.filter((item) => item !== payload)
      state.histories = newHistories
      setHistoryStorage(newHistories)
    },
    setSearchResults(state, action: PayloadAction<SearchResults>) {
      state.result = {
        results: [...state.result.results, ...action.payload.results],
        total_count: action.payload.total_count
      }
    }
  }
})

export const { setSuggestion, setHistories, clearHistories, delHistory, setSearchResults } =
  searchSlice.actions

// 获取搜索建议
export function getSuggestionAsync(payload: { q: string }) {
  return async (dispatch: AppDispatch) => {
    if (!payload.q) {
      dispatch(setSuggestion([]))
    } else {
      const {
        data: { options }
      } = await DataServe.getSuggestion(payload)
      dispatch(setSuggestion(options))
    }
  }
}
// 获取搜索结果
export function getSearchResultsAsync(payload: { q: string; page: number; per_page?: number }) {
  return async (dispatch: AppDispatch) => {
    const { data } = await DataServe.getSearchResults(payload)
    dispatch(setSearchResults(data))
  }
}
export default searchSlice.reducer
